#!/usr/bin/env python3

import subprocess

MASTER_CMD = '/home/OM_master/master -h {} -p 10086 '
SED_CMD = '\'sed -i \'/"host":/c "host": "{}",\' /home/haohan/importer/conf/home_*\''
KILL_CMD = 'ps -ef | grep importer | grep -v grep | awk \'{print $2}\' | xargs kill -9'


# 定义方法 读取 importer.csv 文件 将第一列赋值为host，后几列用逗号拼接后赋值给ch_host，方法返回一个map
def read_custom_file(file_name):
    importer_ch_map = {}
    with open(file_name, 'r') as f:
        lines = f.readlines()
        for line in lines:
            line = line.strip()
            if line:
                host = line.split('\t')[0]
                ch_host = ':8123,'.join(line.split('\t')[1:])
                importer_ch_map[host] = ch_host + ':8123'

    return importer_ch_map


if __name__ == '__main__':
    # 调用方法并打印结果
    ch_map = read_custom_file('importer.csv')
    # 遍历打印map
    for k, v in ch_map.items():
        ret = subprocess.run(['echo', MASTER_CMD, '-h', k, '-p 10086 -s', SED_CMD.format(v)])
        if ret.returncode == 0:
            print("success:", ret)
        else:
            print("error:", ret)

        kill = subprocess.run([KILL_CMD])
        if kill.returncode == 0:
            print("success:", kill)
        else:
            print("error:", kill)
            